<template>
  <div class="box">
    <div class="title">
      <div><img src="~assets/logo.svg" alt=""></div> 
      <div>&nbsp;达英尔书写质量评判平台</div> 
    </div>
    <div class="login">
      <div class="avatar">
        <img class="img" :src="[ isShow ? getUserAvatar : defaultUrl ]" alt="">
      </div>
      <!-- <div class="nickname" v-show="isShow">{{ this.userInfo.nickname }}</div> -->
      <el-button v-if="isShow" @click="logout" type="danger">注销</el-button>
      <el-button v-else @click="login" type="primary">登录</el-button>
    </div>

    <!-- 弹出框 -->
    <el-dialog
        v-model="showDialog"
        title="请指定用户名"
        width="30%">
      <el-input placeholder="请输入用户名" v-model="username"></el-input>
      <template #footer>
        <span>
          <el-button type="primary" @click="addUserName">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
  import { ElMessage } from 'element-plus'

  export default {
    data() {
      return {
        showDialog: false,
        username: '',

        defaultUrl: require('assets/user.svg'),
        isShow: false,
        state: '',
        openid: '',

        user: {
          openid: '',
          headimgurl: '',
          username: ''
        },

        userInfo: {
          openid: window.sessionStorage.openid,
          nickname: window.sessionStorage.nickname,
          username: window.sessionStorage.username,
          headimgurl: window.sessionStorage.headimgurl
        }
      }
    },
    computed: {
      getUserAvatar() {
        return this.$store.state.userInfo.headimgurl
      }
    },
    // watch: {
    //   'openid': async function() {
    //     if (this.openid) {
    //         let resUserInfo = await this.axios.get(`http://wuwei.dayaar.com.cn:5432/getUser/${this.openid}`)
    //         console.log(resUserInfo.data);

    //         // this.user = resUserInfo.data
    //       }
    //   }
    // },
    methods: {
      // 提示用户登录
      promptLogin() {
        ElMessage.warning('请登录后操作')
      },

      // 显示微信二维码, 进行扫码登录
      async login() {
        try {
          // 生成一个唯一 state
          this.state = new Date().getTime()

          // 把 state 存入 sessionStorage  
          window.sessionStorage.setItem('state', this.state)

          let res = await this.axios.get(`http://wuwei.dayaar.com.cn:5432/openQrcode/${this.state}`)        
          console.log(res.data);

          window.location.href = res.data

        } catch(err) {
          console.log(err);
        }
      },

      // 获取用户信息
      async getUser() {
        try {
          let resOpenid = await this.axios.get(`http://wuwei.dayaar.com.cn:5432/getOpenid/${window.sessionStorage.state}`)
          this.openid = resOpenid.data.openid

          // 判断 是否获取到 openid
          if (resOpenid.data.openid) {
            let resUserInfo = await this.axios.get(`http://wuwei.dayaar.com.cn:5432/getUser/${resOpenid.data.openid}`)
            this.user = resUserInfo.data
            console.log(this.user);
          }

          if (this.user.openid) {
            // 更改 【头像】【按钮】 登录样式
            this.isShow = true
            
            this.user.username ?
              ElMessage.success({
                message: `欢迎 ${this.user.username}`,
                center: true
              }) :
              ElMessage.success({
                message: '欢迎登录，请创建用户名',
                center: true
              })
             
            // 在 vuex 中存储用户信息
            this.$store.commit('setUser', this.user)

            // 向父组件 Home.vue 发送登录成功状态
            this.$emit('userLogin', { login: true })

            window.sessionStorage.setItem('openid', this.user.openid)
            window.sessionStorage.setItem('headimgurl', this.user.headimgurl)
            window.sessionStorage.setItem('username', this.user.username)
          } else {
            window.sessionStorage.clear();
            ElMessage.error('登录失败');
            return
          }

          !this.user.username ? this.showDialog = true : this.showDialog = false
        } catch(err) {
          console.log(err);     
        }
      },

      // 添加 username
      async addUserName() {
        let respon = await this.axios.patch(`http://wuwei.dayaar.com.cn:5432/addUserName/${this.user.openid}/${this.username}`)
        .then(res => {
          window.location.reload()

          ElMessage.success({
            message: `欢迎  ${res.data}`,
            center: true
          })
        })

        window.sessionStorage.setItem('username', this.username)

        // 向父组件 Home.vue 发送登录成功状态
        this.$emit('setUserName', { username: this.username})

        this.showDialog = false
      },


      // 退出登录
      async logout() {
        // header 显示未登录状态
        this.isShow = false
        // 清空 sessionStorage
        window.sessionStorage.clear()
        // 清空 路由中的参数
        this.$router.push({ path: '/' })

        this.$emit('userLogin', { login: false })
      }
    },
    mounted() {
      // 把这一步做成异步执行： 后端有响应时才执行 getUser()
      window.sessionStorage.state ? this.getUser() : this.promptLogin();
    }
  }
</script>

<style lang="less" scoped>
  .box {
    width: 100%;
    padding: 15px 20px;
    background-color: #1f2d3d;
    text-align: center;
    display: flex;
    justify-content: space-between;

    .title {
      font-size: 30px;
      color: #fff;
      display: flex;
      justify-content: space-around;
      align-items: center;
    }
    .login {
      width: 130px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .avatar {
        width: 40px;
        height: 40px;
        background-color: #fff;
        border-radius: 50%;
        .img {
          width: 100%;
        }
      }
      .nickname {
        color: #fff;
        font-size: 20px;
        margin-right: 20px;
      }
    }
  }
</style>